package com.topvision.auth.controller;

import com.topvision.auth.domain.SysUser;
import com.topvision.auth.dto.UserDTO;
import com.topvision.auth.service.SysUserService;
import com.topvision.common.response.SuccessResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Optional;

/**
 * Created by wangyunfei on 2017/6/12.
 */
@RestController
@RequestMapping("/user")
@Api(value = "用户相关API", description = "用户信息相关修改API")
@Slf4j
public class UserController {

    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/user")
    public Principal user(Principal user){
        return user;
    }

    @ApiOperation(value = "获取用户信息")
    @RequestMapping(value = "/userInfo", method = RequestMethod.POST)
    public ResponseEntity userInfo(Principal principal) {
        String userName = principal.getName();
        Optional<SysUser> sysUser = Optional.empty();
        if (userName != null) {
            sysUser = sysUserService.findByUserName(userName);
        }
        return sysUser.map(user -> {
            return ResponseEntity.ok().body(SuccessResponse.of(user));
        }).orElse(ResponseEntity.ok().body(SuccessResponse.of("empty")));
    }


    @ApiOperation(value = "修改个人信息")
    @RequestMapping(value = "/profile", method = RequestMethod.POST)
    public ResponseEntity profile(@RequestBody UserDTO userDTO, Principal principal) {

        String userName = principal.getName();
        Optional<SysUser> sysUser = Optional.empty();
        if (userName != null) {
            sysUser = sysUserService.findByUserName(userName);
        }
        return sysUser.map(user -> {
            if (StringUtils.isNotBlank(userDTO.getMobile())) {
                user.setMobile(userDTO.getMobile());
            }

            if (StringUtils.isNotBlank(userDTO.getAddress())) {
                user.setAddress(userDTO.getAddress());
            }
            if (StringUtils.isNotBlank(userDTO.getCompany())) {
                user.setCompany(userDTO.getCompany());
            }

            if (StringUtils.isNotBlank(userDTO.getJobTitle())) {
                user.setJobTile(userDTO.getJobTitle());
            }

            if (StringUtils.isNotBlank(userDTO.getTrueName())) {
                user.setTrueName(userDTO.getTrueName());
            }

            sysUserService.save(user);
            return ResponseEntity.ok().body(SuccessResponse.of());
        }).orElse(ResponseEntity.ok().body(SuccessResponse.of()));
    }
}